#!/bin/bash

# ANSI 颜色码定义
RED='\033[0;31m'    # 红色
GREEN='\033[0;32m'  # 绿色
BLUE='\033[0;34m'   # 蓝色
NC='\033[0m'        # 无颜色

# 处理 curl: (6) Could not resolve host 错误的函数
resolve_dns_issue() {
    echo -e "${RED}检测到 DNS 解析错误，正在修复...${NC}"
    if ! grep -q "nameserver 8.8.8.8" /etc/resolv.conf; then
        echo "nameserver 8.8.8.8" | sudo tee -a /etc/resolv.conf
    fi
    if ! grep -q "nameserver 8.8.4.4" /etc/resolv.conf; then
        echo "nameserver 8.8.4.4" | sudo tee -a /etc/resolv.conf
    fi
    echo -e "${GREEN}DNS 解析错误已修复，继续执行...${NC}"
}

# 封装 curl 和 wget 命令，自动处理 DNS 解析错误并重试
execute_command() {
    local cmd="$1"
    eval "$cmd"
    if [ $? -ne 0 ]; then
        resolve_dns_issue
        eval "$cmd"
    fi
}

# 更换软件源的函数
change_sources() {
    echo -e "${GREEN}请选择要更换的软件源：${NC}"
    echo -e "${GREEN}1. 网易源${NC}"
    echo -e "${GREEN}2. 阿里源${NC}"
    echo -e "${GREEN}3. 清华源${NC}"
    read -p "输入选择的编号 (1/2/3): " source_choice

    # 定义不同源的 URL
    case "$source_choice" in
        1)
            NEW_SOURCES_URL="https://gitee.com/t88t/test/raw/master/debian12-163-sources.list"
            ;;
        2)
            NEW_SOURCES_URL="https://gitee.com/t88t/test/raw/master/debian12-aliyun-sources.list"
            ;;
        3)
            NEW_SOURCES_URL="https://gitee.com/t88t/test/raw/master/debian12-tsinghua-sources.list"
            ;;
        *)
            echo "无效的选择，请重新运行脚本并选择 1/2/3。"
            return
            ;;
    esac

    # 检查是否已经存在备份文件
    if [ ! -f /etc/apt/sources.list.bak ]; then
        echo "正在备份当前的 sources.list 到 sources.list.bak..."
        sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
    else
        echo "已存在备份文件 sources.list.bak，跳过备份。"
    fi

    # 下载新的 sources.list
    echo "正在下载新的 sources.list..."
    wget -O /opt/debian-sources.list "$NEW_SOURCES_URL"

    # 检查下载是否成功
    if [ $? -ne 0 ]; then
        echo "下载新的 sources.list 失败，请检查 URL 是否正确。"
        exit 1
    fi

    # 替换当前的 sources.list
    echo "正在替换当前的 sources.list..."
    sudo mv /opt/debian-sources.list /etc/apt/sources.list

    # 更新软件包列表
    echo "正在更新软件包列表..."
    sudo apt update
    echo "软件源更换完成。"
    # 返回选择页面
    return_to_menu
}

modify_host() {
    # 备份 /etc/hosts 文件
    if [ ! -f /etc/host_back ]; then
        sudo cp /etc/hosts /etc/host_back
        echo "Backup created: /etc/host_back"
    else
        echo "Backup already exists: /etc/host_back"
    fi

    # 修改 /etc/hosts 文件
    # 检查是否已安装 curl 命令
    if ! command -v curl &> /dev/null; then
        echo -e "${RED}检测到没有安装 curl，正在安装...${NC}"
        echo "安装 curl 命令..."
        sudo apt-get install -y curl
    fi
    execute_command "sudo sh -c 'sed -i \"/# GitHub520 Host Start/Q\" /etc/hosts && curl https://raw.githubusercontent.com/hosts/main/hosts >> /etc/hosts'"
    echo "/etc/hosts 文件修改完成..."

    # 创建定时任务文件
    local cron_file="/opt/cron_job"
    local cron_job="0 * * * * /usr/bin/curl -s https://raw.githubusercontent.com/hosts/main/hosts >> /etc/hosts; echo \$(date) >> /opt/cron_count.txt"

    # 清理任何已有的定时任务
    (crontab -l 2>/dev/null | grep -v "curl -s https://raw.githubusercontent.com/hosts/main/hosts" | crontab -)

    # 设置定时任务
    echo "$cron_job" > $cron_file
    crontab $cron_file

    echo -e "${GREEN}定时任务已设置，每小时运行一次，总共更新 2 次 host 后，自动关闭更新。${NC}"

    # 检查是否已安装 at 命令
    if ! command -v at &> /dev/null; then
        echo -e "${RED}检测到没有安装 at，正在安装...${NC}"
        echo "安装 at 命令..."
        sudo apt-get install -y at
    fi

    # 使用 at 命令在 2 小时后移除定时任务
    echo '(crontab -l 2>/dev/null | grep -v "curl -s https://raw.githubusercontent.com/hosts/main/hosts" | crontab -)' | at now + 2 hours

    # 返回选择页面
    return_to_menu
}

# 安装 Docker 的函数
install_docker() {
    echo "更新依赖..."
    sudo apt update

    echo "安装必要依赖..."
    sudo apt install -y curl software-properties-common

    echo "添加官方密钥..."
    curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -

    echo "安装 Docker 源镜像..."
    sudo add-apt-repository -y "https://download.docker.com/linux/debian $(lsb_release -cs) stable"

    echo "安装 Docker 与 Docker Compose..."
    sudo apt install -y docker-ce docker-ce-cli containerd.io docker-compose

    echo "启动 Docker..."
    sudo systemctl start docker
    # 查看 Docker 启动情况
    sudo systemctl status docker

    echo "设置开机启动 Docker..."
    sudo systemctl enable docker
    echo "Docker 设置完毕"

    docker version
    docker-compose version

    sudo systemctl daemon-reload
    sudo systemctl restart docker
}

# 安装 SRT 的函数
install_srt() {
    echo -e "${GREEN}请选择要安装的版本：${NC}"
    echo -e "${GREEN}1. 5.4${NC}"
    echo -e "${GREEN}2. 6.1${NC}"
    read -p "输入选择的版本编号 (1/2): " kernel_choice

    if [ "$kernel_choice" == "1" ]; then
        kernel_version="5.4"
    elif [ "$kernel_choice" == "2" ]; then
        kernel_version="6.1"
    else
        echo "无效的选择。请重新运行脚本并选择 1 或 2。"
        return
    fi

    execute_command "wget -O - https://www.openmptcprouter.com/server/debian-x86_64.sh | KERNEL=\"$kernel_version\" sh"
    echo "看到这个才安装成功 You need to reboot to enable MPTCP, glorytun and shorewall"
    echo "若安装成功，请重启服务器，重启后 ssh 端口为：65222"
}

# 安装 SRS 的函数
install_srs() {
    echo -e "${GREEN}请选择安装方式：${NC}"
    echo -e "${GREEN}1. Docker 版${NC}"
    echo -e "${GREEN}2. 编译版${NC}"
    read -p "输入选择的编号 (1/2): " srs_choice

    case "$srs_choice" in
        1)
            # 检查 Docker 是否已安装
            if ! command -v docker &> /dev/null; then
                echo -e "${RED}Docker 未安装，正在安装 Docker...${NC}"
                install_docker
            fi

            echo "正在安装 SRS（Docker 版）..."
            docker run --restart always -d -it --name oryx -v $HOME/data:/data \
            -p 2021:2022 -p 443:2443 -p 1935:1935 -p 8000:8000/udp -p 10080:10080/udp \
            registry.cn-hangzhou.aliyuncs.com/ossrs/oryx:5

            if [ $? -eq 0 ]; then
                echo "SRS（Docker 版）安装并启动成功。后台地址 http://ip:2021 "
            else
                echo -e "${RED}SRS（Docker 版）安装或启动失败。${NC}"
            fi
            ;;
        2)
            # 检查依赖是否安装
            echo -e "${GREEN}检查依赖是否安装...${NC}"
            if ! command -v git &> /dev/null; then
                echo "Git 未安装，开始安装 Git..."
                if ! sudo apt-get install -y git; then
                    echo "安装 Git 失败，退出脚本。"
                    exit 1
                fi
            else
                echo "Git 已安装。"
            fi

            if ! command -v gcc &> /dev/null; then
                echo "gcc 未安装，开始安装 gcc..."
                sudo apt-get install -y gcc
            else
                echo "gcc 已安装。"
            fi

            if ! command -v make &> /dev/null; then
                echo "make 未安装，开始安装 make..."
                sudo apt-get install -y make
            else
                echo "make 已安装。"
            fi

            if ! command -v g++ &> /dev/null; then
                echo "g++ 未安装，开始安装 g++..."
                sudo apt-get install -y g++
            else
                echo "g++ 已安装。"
            fi

            if ! command -v automake &> /dev/null; then
                echo "automake 未安装，开始安装 automake..."
                sudo apt-get install -y automake
            else
                echo "automake 已安装。"
            fi

            if ! command -v tclsh &> /dev/null; then
                echo "tclsh 未安装，开始安装 tclsh..."
                sudo apt-get install -y tclsh
            else
                echo "tclsh 已安装。"
            fi

            if ! command -v cmake &> /dev/null; then
                echo "cmake 未安装，开始安装 cmake..."
                sudo apt-get install -y cmake
            else
                echo "cmake 已安装。"
            fi

            if ! command -v pkg-config &> /dev/null; then
                echo "pkg-config 未安装，开始安装 pkg-config..."
                sudo apt-get install -y pkg-config
            else
                echo "pkg-config 已安装。"
            fi

            echo "正在安装 SRS（编译版）..."
            git clone -b develop https://gitee.com/ossrs/srs.git
            cd srs/trunk
            ./configure
            make
            cd /root/srs/trunk
            ./objs/srs -c conf/srs.conf
            ./etc/init.d/srs status
            echo "启动完成，tail -n 30 -f./objs/srs.log查看日志 "
            echo "官方地址：https://ossrs.net/lts/zh-cn/docs/v5/doc/getting-started-build"
            ;;
        *)
            echo "无效的选择。请重新选择 1 或 2。"
            return
            ;;
    esac

    # 返回选择页面
    return_to_menu
}

# 返回主菜单的函数
return_to_menu() {
    echo -e "${GREEN}请选择操作：${NC}"
    echo -e "${GREEN}1. 更换软件源${NC}"
    echo -e "${GREEN}2. 修改 HOST${NC}"
    echo -e "${GREEN}3. 安装 聚合VPS端${NC}"
    echo -e "${GREEN}4. 安装 SRS${NC}"
    echo -e "${GREEN}0. 退出${NC}"
    read -p "输入选择的编号 (0-4): " choice

    case "$choice" in
        1)
            change_sources
            ;;
        2)
            modify_host
            ;;
        3)
            install_srt
            ;;
        4)
            install_srs
            ;;
        0)
            echo "退出脚本。"
            exit 0
            ;;
        *)
            echo "无效的选择。请重新选择 0 到 4 之间的编号。"
            return_to_menu
            ;;
    esac
}

# 启动脚本并显示主菜单
return_to_menu